package spring.springsecurety.userdetilService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import zhang.dao.Entities.domainZhang;
import zhang.dao.Entities.userLiSi;
import zhang.dao.mapper.MybatisMapperLisi;
import zhang.dao.mapper.MybatisMapperZhang;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService implements UserDetailsService {


    @Autowired
    private MybatisMapperZhang mybatisUsername;  //用户密码
    @Autowired
    private MybatisMapperLisi mybatisQuanXian;  //权限

    @Autowired
    private PasswordEncoder passwordEncoder;


//    @PostConstruct
//    public void initData() {
//        String password = passwordEncoder.encode("123456");
//        userList = new ArrayList<>();
//        userList.add(new User("macro", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
//        userList.add(new User("andy", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
//        userList.add(new User("mark", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
//    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        domainZhang domainZhang = mybatisUsername.selectZhang(username);//获取用户信息
        userLiSi userLiSi = mybatisQuanXian.selectLisi(username); //获取用户权限信息
        String quanxian=userLiSi.getQuanxian();
        String[] split = quanxian.split(",");

        UserDetails user = User.withUsername(domainZhang.getUsername())
                .password(domainZhang.getPassword())
                .roles(split).build();


        return user;
    }
}
